import os
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.text_splitter import RecursiveCharacterTextSplitter
from typing import List

# 嵌入模型全局复用
embedding_model = OllamaEmbeddings(model="nomic-embed-text")

# 文本切分器
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=100,
    chunk_overlap=20
)

def build_vectorstore_from_text(text: str) -> FAISS:
    """
    将纯文本构建为 FAISS 向量数据库对象。
    """
    chunks = text_splitter.split_text(text)
    vectorstore = FAISS.from_texts(chunks, embedding_model)
    return vectorstore

def save_vectorstore_to_disk(vectorstore: FAISS, persist_path: str):
    """
    将 FAISS 向量库保存至磁盘。
    """
    vectorstore.save_local(persist_path)

def load_vectorstore_from_disk(path):
    return FAISS.load_local(
        path,
        embeddings=embedding_model,
        allow_dangerous_deserialization=True
    )